import { Suspense, useState, useEffect } from 'react';
import { useRoutes, useNavigate, Outlet } from 'react-router-dom';

import routes from '../../router/index';
import { DownOutlined, CaretDownOutlined } from '@ant-design/icons';
import { Skeleton, Dropdown, Space, Button } from 'antd';

import '../../index.model.css';
import axios from 'axios';

let Navpage = () => {
  let routerView = useRoutes(routes);
  let navigate = useNavigate();

  useEffect(() => {
    getnav();
  }, []);

  // 选中的导航项索引，默认为第一个导航项
  const [selectedIndex, setSelectedIndex] = useState(0);
  let [navleft, setnavleft] = useState([]);
  // 新增状态变量，用于存储选中导航项的子级数据
  let [selectedChildren, setSelectedChildren] = useState([]);
  // 选中的二级导航项索引，默认为第一个二级导航项
  const [selectedChildIndex, setSelectedChildIndex] = useState(0);
  // 记录是否已经完成初始导航
  const [isInitialNavigated, setIsInitialNavigated] = useState(false);
  //获取用户名
  const username = sessionStorage.getItem('username');
  //获取角色ID
  const role = sessionStorage.getItem('roleID');
  console.log(role,'111111111111111111111111111111111111111111111111111111111111111');
  
  let getnav = () => {
    axios.get(`http://127.0.0.1:3000/chen/render?id=${role}`).then(res => {
      console.log('从服务器获取的导航数据:', res.data.data);
      setnavleft(res.data.data);
      
    });
  };

  // 点击导航项时改变背景颜色
  const handleNavClick = (index, path) => {
    console.log(index);
    setSelectedIndex(index);  // 设置选中的导航项索引
    // 更新选中导航项的子级数据
    const children = navleft[index]?.children || [];
    setSelectedChildren(children);
    if (children.length > 0) {
      setSelectedChildIndex(0); // 重置二级导航选中的索引
      navigate(children[0].url);  // 导航到第一个二级导航的路径
    } else {
      navigate(path);  // 没有子级则导航到当前导航项路径
    }
  };

  // 点击二级导航项时改变背景颜色
  const handleChildNavClick = (childIndex, path) => {
    setSelectedChildIndex(childIndex); // 设置选中的二级导航项索引
    navigate(path);  // 导航到相应的路径
  };
  const Outlogin=()=>{
    navigate('/chen/login')
    sessionStorage.clear();
  }
  const items = [
    {
      label: (
        <a href="https://www.antgroup.com" target="_blank" rel="noopener noreferrer">
          个人资料
        </a>
      ),
      key: '0',
    },
    {
      label: (
        <a href="https://www.aliyun.com" target="_blank" rel="noopener noreferrer">
          修改密码
        </a>
      ),
      key: '1',
    },
    {
      label: (
        <a onClick={Outlogin} target="_blank" rel="noopener noreferrer">
          退出系统
        </a>
      ),
      key: '2',
    },
  ];

  // 自动导航到第一个二级路由
  useEffect(() => {
    if (!isInitialNavigated && navleft.length > 0) {
      const firstChildren = navleft[0]?.children;
      if (firstChildren && firstChildren.length > 0) {
        setSelectedChildren(firstChildren);
        setSelectedIndex(0);
        setSelectedChildIndex(0);
        navigate(firstChildren[0].url);
        setIsInitialNavigated(true);
      }
    }
  }, [navleft, navigate, isInitialNavigated]);

  return (
    <>
      <Suspense fallback={<div> <Skeleton active /></div>}>
        <div className='box'>

          <div className="left_nav">
            <img className='img_logo' src="https://cdn8.axureshop.com/demo2024/2296569/images/%E6%BC%94%E7%A4%BA%E6%A1%86%E6%9E%B6/u652.svg" alt="" />
            <p className='name_p'>Mila奇迹</p>

            {navleft.map((item, index) => {
              return (
                <div key={item.id}>

                  <button
                    className={`Nav_button ${selectedIndex === index ? 'selected' : ''}`}
                    onClick={() => handleNavClick(index, item.path)}
                  >
                    <img src={item.img} alt="" />
                  </button>

                </div>
              );
            })}

          </div>
          <div className="left_nav_right">
            {/* 渲染选中导航项的子级数据 */}
            {selectedChildren.map((child, childIndex) => (
              <div key={childIndex} className='child_nav_box'>
                <button
                  className={`child_nav_button ${selectedChildIndex === childIndex ? 'selected' : ''}`}
                  onClick={() => handleChildNavClick(childIndex, child.url)}
                >
                  {child.name}
                </button>
              </div>
            ))}
          </div>
          <div className="top_nav">
            <div className="top_nav_item">
              <img className='top_nav_img' src="https://cdn8.axureshop.com/demo2024/2296569/images/%E7%BB%84%E4%BB%B6_%E8%A7%84%E8%8C%83/u416.svg" alt="" />
              <input
                className='top_nav_input'
                placeholder="请输入关键字"
              />
            </div>
            <div className="avatar_box">
              <img className='img_icon' src="https://cdn8.axureshop.com/demo2024/2296569/images/%E7%BB%84%E4%BB%B6_%E8%A7%84%E8%8C%83/u431.svg" alt="" />
              <img className='img_icon' src="https://cdn8.axureshop.com/demo2024/2296569/images/%E7%BB%84%E4%BB%B6_%E8%A7%84%E8%8C%83/u429.svg" alt="" />
              <img className='avatar_img' src="https://cdn8.axureshop.com/demo2024/2296569/images/%E7%BB%84%E4%BB%B6_%E8%A7%84%E8%8C%83/u422.svg" alt="" />
              {/* 使用 Dropdown 组件包裹用户名和下拉箭头 */}
              <Dropdown menu={{ items }} trigger={['click']}>
                <a onClick={(e) => e.preventDefault()}>
                  <Space>
                    <p className='Username'>{username}</p>
                    <CaretDownOutlined className='CaretDownOutlined' />
                  </Space>
                </a>
              </Dropdown>
            </div>
          </div>
          <div className="content_box">
            <Outlet />
          </div>
        </div>
      </Suspense>
    </>
  );
};

export default Navpage;